# -*- coding: utf-8 -*-
"""
Created on Mon Apr 18 19:04:47 2022

@author: Apple
"""

import os
import sys
from PyQt5.QtWidgets import (QAbstractItemView,QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem,QHeaderView)
from main_window import Ui_MainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import re

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.actionopen.triggered.connect(self.openfile)
        self.ui.actionversion.triggered.connect(self.showversion)
        self.ui.btn11.clicked.connect(lambda:self.inputnum(1)) 
        self.ui.btn21.clicked.connect(lambda:self.inputnum(2))
        self.ui.btn12.clicked.connect(lambda:self.newrow(tw1))
        self.ui.btn22.clicked.connect(lambda:self.newrow(tw2))
        self.ui.btn13.clicked.connect(lambda:self.delrow(tw1))
        self.ui.btn23.clicked.connect(lambda:self.delrow(tw2))
        self.ui.btn14.clicked.connect(lambda:self.savedata(tw1))
        self.ui.btn24.clicked.connect(lambda:self.savedata(tw2))
        self.ui.btn15.clicked.connect(lambda:self.cleartable(1))
        self.ui.btn25.clicked.connect(lambda:self.cleartable(2))
        self.ui.btnS1.clicked.connect(lambda:self.read_data(1))
        self.ui.btnS2.clicked.connect(lambda:self.read_data(2))
        self.ui.btnS3.clicked.connect(lambda:self.read_data(3))
        self.ui.btnS4.clicked.connect(lambda:self.cleartable(3))
        self.ui.btnO1.clicked.connect(lambda:self.read_data(4))
        self.ui.btnO3.clicked.connect(lambda:self.cleartable(4))
        
        # 初始化表格1
        tw1 = self.ui.tableWidget1
        tw1.setRowCount(1)
        tw1.setColumnCount(10)
        tw1.setHorizontalHeaderLabels(['配送日期','站点代码','站点名称','罐号','油品代码','油品名称','升数（升）','数量（公斤）','配送中心代码','配送中心名称'])
        tw1.setEditTriggers(QTableWidget.CurrentChanged)
        for i in range(10):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw1.setItem(0,i,newItem)
        
        # 初始化表格2
        tw2 = self.ui.tableWidget2
        tw2.setRowCount(1)
        tw2.setColumnCount(7)
        tw2.setHorizontalHeaderLabels(['所属区域','站点代码','站点名称','营业状态','经度','纬度','配送优先级'])
        tw2.setEditTriggers(QTableWidget.CurrentChanged)
        for i in range(10):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw2.setItem(0,i,newItem)
        
    # 打开本地文件
    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    # 展示当前版本
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版本为 V1.0 ')
    
    # 输入站点个数
    def inputnum(self,model):
        if model == 1:
            num = self.ui.num_of_order.text()
            if num.isdigit() != True :
                print('Please input an *integer*')
                QMessageBox.about(self, '警告', '请输入一个正整数')
                return
            tw1 = self.ui.tableWidget1
            tw1.setRowCount(int(num))
            for i in range(int(num)):
                for j in range(10):
                    newItem = QTableWidgetItem('')
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw1.setItem(i,j,newItem)
        elif model == 2:
            num = self.ui.num_of_station.text()
            if num.isdigit() != True :
                print('Please input an *integer*')
                QMessageBox.about(self, '警告', '请输入一个正整数')
                return
            tw2 = self.ui.tableWidget2
            tw2.setRowCount(int(num))
            for i in range(int(num)):
                for j in range(7):
                    newItem = QTableWidgetItem('')
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw1.setItem(i,j,newItem)
    
    # 新增一行
    def newrow(self,tw):
        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        tableWidget.insertRow(numrow)
        for i in range(numcol):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(numrow,i,newItem)
            
    # 删除一行
    def delrow(self,tw):

        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        if numrow == 1:
            tableWidget.removeRow(0)
            tableWidget.insertRow(0)
            for i in range(numcol):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget.setItem(0,i,newItem)            
        else:
            tableWidget.removeRow(numrow-1)
    
    # 保存当前输入
    def savedata(self,tw):
        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget.item(i,j).text()
                listcol.append(data)
                # if data =='':
                #     QMessageBox.about(self, '警告', '请输入完整数据')
                #     return
                # else:
                #     listcol.append(data)
            listall.append(listcol)
        # print(listall)
        if tw == self.ui.tableWidget1:
            path = os.getcwd() + r'\test.csv'
        else:
            path = os.getcwd() + r'\test.csv'
        # print(path)
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')   
            
    # 清空表格内容
    def cleartable(self,model):
        
        if model == 1:
            title = ['配送日期','站点代码','站点名称','罐号','油品代码','油品名称','升数（升）','数量（公斤）','配送中心代码','配送中心名称']
            tw1 = self.ui.tableWidget1
            tw1.clear()
            tw1.setRowCount(1)
            tw1.setColumnCount(10)
            for i in range(10):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw1.setItem(0,i,newItem)
            
            tw1.setHorizontalHeaderLabels(title)
            tw1.setEditTriggers(QTableWidget.CurrentChanged)
            
        if model == 2:
            title = ['所属区域','站点代码','站点名称','营业状态','经度','纬度','配送优先级']
            tw2 = self.ui.tableWidget2
            tw2.clear()
            tw2.setRowCount(1)
            tw2.setColumnCount(7)
            tw2.setEditTriggers(QTableWidget.CurrentChanged)
            for i in range(10):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw2.setItem(0,i,newItem)
            
            tw2.setHorizontalHeaderLabels(title)
            tw2.setEditTriggers(QTableWidget.CurrentChanged)
        
        if model == 3:
            tw = self.ui.tableWidget4
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
        
        if model == 4:
            tw = self.ui.tableWidget
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
    
    def read_data(self,model):
        if model == 1:
            title = ['配送日期','站点代码','站点名称','罐号','油品代码','油品名称','升数（升）','数量（公斤）','配送中心代码','配送中心名称']
            tw = self.ui.tableWidget4
            data = pd.read_csv(r'test1.csv')
            Data = data.iloc[:,:].values.tolist() # 转换为list
            tw.setRowCount(len(Data))
            tw.setColumnCount(10)
            tw.setHorizontalHeaderLabels(title)
            tw.setEditTriggers(QTableWidget.CurrentChanged)
            
            for i in range(1,len(Data)):
                for j in range(10):
                    newItem = QTableWidgetItem(str(data.iloc[i,j]))
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw.setItem(i,j,newItem)
        if model == 2:
            title = ['所属区域','站点代码','站点名称','营业状态','经度','纬度','配送优先级']
            tw = self.ui.tableWidget4
            data = pd.read_csv(r'test2.csv')
            Data = data.iloc[:,:].values.tolist() # 转换为list
            tw.setRowCount(len(Data))
            tw.setColumnCount(7)
            tw.setHorizontalHeaderLabels(title)
            tw.setEditTriggers(QTableWidget.CurrentChanged)
            
            for i in range(1,len(Data)):
                for j in range(7):
                    newItem = QTableWidgetItem(str(data.iloc[i,j]))
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw.setItem(i,j,newItem)
        
        if model == 3:
            tw = self.ui.tableWidget4
            data = pd.read_csv(r'test3.csv')
            tw.setRowCount(len(data))
            tw.setColumnCount(len(data))
            tw.setHorizontalHeaderLabels(data.columns.tolist()[1:])
            tw.setVerticalHeaderLabels(data.columns.tolist()[1:])
            
            for i in range(len(data)):
                for j in range(1,len(data)):
                    newItem = QTableWidgetItem(str(data.iloc[i,j]))
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw.setItem(i,j-1,newItem)
                    
        if model == 4:
            tw = self.ui.tableWidget
            data = pd.read_csv(r'test4.csv')
            tw.setRowCount(len(data))
            tw.setColumnCount(len(data.columns))
            tw.setHorizontalHeaderLabels(data.columns.tolist())
            
            for i in range(len(data)):
                for j in range(len(data.columns)):
                    newItem = QTableWidgetItem(str(data.iloc[i,j]))
                    newItem.setTextAlignment(Qt.AlignCenter)
                    tw.setItem(i,j,newItem)

        
if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())